package com.atguigu.tingshu.user.pattren.impl;

import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.pattren.DeliveryStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: jack
 * @date: 2025/10/14 19:16
 */

@Component(SystemConstant.ORDER_ITEM_TYPE_TRACK)
@Slf4j
public class TrackDelivery implements DeliveryStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Override
    public void delivery(UserPaidRecordVo userPaidRecordVo) {

        log.info("开始处理声音购买");
        //2. 判断声音是否被购买过
        Long count = userPaidTrackMapper.selectCount(
                new LambdaQueryWrapper<UserPaidTrack>()
                        .in(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo())
        );
        if (count > 0) {
            return;
        }
        //2.1 为用户发放权益
        TrackInfo trackInfo =
                albumFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0)).getData();
        Long albumId = trackInfo.getAlbumId();
        //2.3 新增订单记录即可
        userPaidRecordVo.getItemIdList().stream().forEach(itemId ->
                {
                    UserPaidTrack userPaidTrack = new UserPaidTrack();
                    userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                    userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                    userPaidTrack.setTrackId(itemId);
                    userPaidTrack.setAlbumId(albumId);
                    userPaidTrackMapper.insert(userPaidTrack);
                }
        );

    }
}
